package com.xbfinal.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @version 1.0
 * @Author 笑霸final
 * @Date 2023/10/18 18:28
 * @注释 HTTP相关工具类
 */
public class HttpUtils {

    /**
     * 分块下载的获取链接
     * @param url
     * @param startPost
     * @param startEnd
     * @return
     */

    public static HttpURLConnection getHttpUrlConnection(String url,long startPost,long startEnd) throws IOException {
        HttpURLConnection httpUrlConnection = getHttpUrlConnection(url);
        System.out.println("下载的区间是"+startPost+"-"+startEnd );
        if(startEnd != 0){
            //第一块+中间数据块
            httpUrlConnection.setRequestProperty("RANGE","bytes="+startPost+"-"+startEnd);
        }else{
            //最后一块的数据
            httpUrlConnection.setRequestProperty("RANGE","bytes="+startPost+"-");
        }
        return httpUrlConnection;
    }


    /**
     * 获取 HttpURLConnection 链接对象
     * @param url
     * @return
     * @throws IOException
     */
    public static HttpURLConnection getHttpUrlConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        //获取链接
        URLConnection urlConnection = httpUrl.openConnection();
        //向网站所在的服务器发送标识信息
        urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.46");

        return (HttpURLConnection)urlConnection;
    }

    /**
     * 获取文件名
     * @param url
     * @return
     */
    public static String getHttpFileName(String url){
        int index = url.lastIndexOf("/");
        return url.substring(index+1);
    }

    public static long getHttpFileLength(String url) throws IOException {
        HttpURLConnection httpUrlConnection= null;
        try{
             httpUrlConnection = getHttpUrlConnection(url);
             return httpUrlConnection. getContentLengthLong();
        }finally {
            assert httpUrlConnection != null;
            httpUrlConnection.disconnect();
        }

    }
}
